import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../components/Login'
import home from '../views/Home'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/home',
    name: 'home',
    component: home
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    // component: () => import(/* webpackChunkName: "about" */ '../views/Home.vue')
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = new VueRouter({
  routes
})
// window.sessionStorage.setItem('token', 'dd')
router.beforeEach((to, from, next) => {
  // to 将要访问的路劲
  // from 代表从哪个路劲跳转而来
  // next 是一个函数，表示放行，执行下一个操作
  // next()放心   next('/login')强制跳转
  console.log(1)
  if (to.path === '/login') return next()
  // // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) {
    return next('/login')
  }
  next()
})

export default router
